//
//  CameraScanOCR.swift
//  Scaner
//
//  Created by liyahao on 2025/4/8.
//

import SwiftUI
import Vision

struct CameraScanOCR {
    var image: UIImage
    @State var setScanTitle: Bool = false
    
    // 开始OCR
    func performOcr() {
        // Get the CGImage on which to perform requests.
        guard let cgImage = image.cgImage else { return }
        
        // Create a new image-request handler.
        let requestHandler = VNImageRequestHandler(cgImage: cgImage)
        
        // Create a new request to recognize text.
        let request = VNRecognizeTextRequest(completionHandler: recognizeTextHandler)
        
        request.recognitionLevel = .accurate
        
        request.automaticallyDetectsLanguage = true
        request.revision = VNRecognizeTextRequestRevision3
        
        request.usesLanguageCorrection = true
        
        print("#OCR: VNRecognizeTextRequestRevision: \(request.revision)")
        
        do {
            // Perform the text-recognition request.
            try requestHandler.perform([request])
        } catch {
            print("Unable to perform the requests: \(error).")
        }
    }
    
    func recognizeTextHandler(request: VNRequest, error: Error?) {
        guard let observations =
                request.results as? [VNRecognizedTextObservation] else {
            return
        }
        let recognizedStrings = observations.compactMap { observation in
            // Return the string of the top VNRecognizedText instance.
            return observation.topCandidates(1).first?.string
        }
        
        // Process the recognized strings.
        processOcrResults(recognizedStrings)
        saveContext()
    }
    
    func processOcrResults(_ found: [String]) {
        
    }
    
    func saveContext() {
       
    }
}


